﻿using System;
using System.Configuration;

namespace JeanFish.Common
{
    /// <summary>
    /// 对异常进行额外的处理
    /// </summary>
    public static class ExceptionHelper
    {
        public class ExceptionEventArgs:EventArgs
        {
            public string Comment{get;set;}
        }
        public delegate void ExceptionEventHandler(Exception sender,ExceptionEventArgs args);
        
        static ExceptionHelper()
        {

        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="comment">备注</param>
        private static void Log(this Exception ex, string comment = "")
        {
            Console.WriteLine(comment + "@" + DateTime.Now);
            Console.WriteLine(ex.ToString());
        }
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <typeparam name="T">处理异常后返回的结果类型</typeparam>
        /// <param name="ex">异常</param>
        /// <param name="exceptionHandler">异常处理方法</param>
        /// <param name="comment">备注</param>
        /// <returns>处理异常后返回的结果</returns>
        public static T Handle<T>(this Exception ex, Func<Exception, T> exceptionHandler, string comment = "")
        {
            ex.Log(comment);
            return exceptionHandler(ex);
        }
        public static void Handle(this Exception ex, Action<Exception> exceptionHandler, string comment = "")
        {
            ex.Log(comment);
            exceptionHandler(ex);
        }
        /// <summary>
        /// 默认异常处理（抛出异常）
        /// </summary>
        /// <typeparam name="T">处理异常后返回的结果类型</typeparam>
        /// <param name="ex">异常</param>
        /// <returns>处理异常后返回的结果</returns>
        private static T DefaultHandler<T>(this Exception ex)
        {
            throw ex;
        }
        private static void DefaultHandler(this Exception ex)
        {
            //throw ex;
        }
        /// <summary>
        /// 使用默认异常处理（抛出异常）处理异常
        /// </summary>
        /// <typeparam name="T">处理异常后返回的结果类型</typeparam>
        /// <param name="ex">异常</param>
        /// <param name="comment">备注</param>
        /// <returns>处理异常后返回的结果</returns>
        public static T Handle<T>(this Exception ex, string comment = "")
        {
            return ex.Handle<T>(DefaultHandler<T>, comment);
        }
        public static void Handle(this Exception ex, string comment = "")
        {
            ex.Handle(DefaultHandler, comment);
        }
        public static event ExceptionEventHandler ExceptionHandler;
    }
    public class ExceptionHelperConfiguration
    {
        public class ExceptionHelperConfigurationSection:ConfigurationSection
        {

        }
    }
}